package monster.com.cvh.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.PutRequest;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISCameraConfig;
import com.yuyh.library.imgsel.config.ISListConfig;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.bean.GetUserInfoBean;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.StatusBarUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by ASUS on 2018/3/13.
 */

public class UserInfoActivity extends PermissionActivity {
    private static final int REQUEST_CAMERA_CODE = 1222;
    private static final int REQUEST_LIST_CODE = 1223;
    @BindView(R.id.iv_activity_user_info_back)
    ImageView ivActivityUserInfoBack;
    @BindView(R.id.tv_activity_user_info_save)
    TextView tvActivityUserInfoSave;
    @BindView(R.id.iv_activity_user_info_male)
    ImageView ivActivityUserInfoMale;
    @BindView(R.id.iv_activity_user_info_female)
    ImageView ivActivityUserInfoFemale;
    @BindView(R.id.edt_activity_user_info_summary)
    EditText edtActivityUserInfoSummary;
    @BindView(R.id.tv_activity_user_info_sum)
    TextView tvActivityUserInfoSum;
    @BindView(R.id.ll_activity_user_info_male)
    LinearLayout llActivityUserInfoMale;
    @BindView(R.id.ll_activity_user_info_female)
    LinearLayout llActivityUserInfoFemale;
    @BindView(R.id.ativity_user_info_id)
    TextView ativityUserInfoId;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_activity_user_info_id)
    TextView tvActivityUserInfoId;
    @BindView(R.id.tv_activity_user_info_name)
    EditText tvActivityUserInfoName;
    @BindView(R.id.iv_user_info_avatar)
    CircleImageView ivUserInfoAvatar;
    private BaseBottomDialog bottomDialog;
    private File userIcon;
    private String gender = null ;
    private int num = 50 ;
    private List<View> mViews = new ArrayList<>( );
    private GetUserInfoBean getUserInfoBean;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initEvent() {
        //限制字数
        edtActivityUserInfoSummary.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                temp = s;
                System.out.println("s=" + s);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = num - s.length();
                tvActivityUserInfoSum.setText("" + number);
                selectionStart = edtActivityUserInfoSummary.getSelectionStart();
                selectionEnd = edtActivityUserInfoSummary.getSelectionEnd();
                //System.out.println("start="+selectionStart+",end="+selectionEnd);
                if (temp.length() > num) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionStart;
                    edtActivityUserInfoSummary.setText(s);
                    edtActivityUserInfoSummary.setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }

    @Override
    protected void initData() {
        //修改状态栏颜色
        StatusBarUtil.setStatusBarLightMode(UserInfoActivity.this, Color.WHITE);
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        getUserInfo();
    }

    private void getUserInfo() {
        OkGo.<String>get(MyConstant.GET_USER_INFO).params("token", SPUtils.getString(UserInfoActivity.this, "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        getUserInfoBean = gson.fromJson(s, GetUserInfoBean.class);
                        switch (getUserInfoBean.getCode()) {
                            case 1:
                            if (!getUserInfoBean.getData().getName().equals("") && getUserInfoBean != null) {
                                tvActivityUserInfoName.setText(getUserInfoBean.getData().getName());
                            }
                                tvActivityUserInfoId.setText(SPUtils.getString(UserInfoActivity.this,"displayId",""));
                                gender = getUserInfoBean.getData().getGender();
                                if (gender.equals("")){
                                    gender = "女" ;
                                }
                                if (gender.equals("男")) {
                                    ivActivityUserInfoMale.setImageResource(R.mipmap.resume_choose);
                                    ivActivityUserInfoFemale.setImageResource(R.mipmap.resume_unchoose);
                                } else {
                                    ivActivityUserInfoFemale.setImageResource(R.mipmap.resume_choose);
                                    ivActivityUserInfoMale.setImageResource(R.mipmap.resume_unchoose);
                                    if (!getUserInfoBean.getData().getSelf_intro().equals("") && getUserInfoBean != null) {
                                        edtActivityUserInfoSummary.setText(getUserInfoBean.getData().getSelf_intro());
                                    }
                                }
                                Glide.with(UserInfoActivity.this).load(getUserInfoBean.getData().getIcon_file()).into(ivUserInfoAvatar);
                                if (!getUserInfoBean.getData().getSelf_intro().equals("")) {
                                    edtActivityUserInfoSummary.setText(getUserInfoBean.getData().getSelf_intro());
                                }
                                break;
                        }
                    }
                });
    }


    private void openGarllary() {
        bottomDialog = BottomDialog.create(getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                bottomDialog.dismiss();
                            }
                        });
                        v.findViewById(R.id.iv_takephoto).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ISCameraConfig config = new ISCameraConfig.Builder()
                                        .needCrop(true) // 裁剪
                                        .cropSize(1, 1, 200, 200)
                                        .build();

                                ISNav.getInstance().toCameraActivity(UserInfoActivity.this, config, REQUEST_CAMERA_CODE);
                                bottomDialog.dismiss();
                            }
                        });
                        v.findViewById(R.id.iv_selectpic).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 自由配置选项
                                ISListConfig config = new ISListConfig.Builder()
                                        // 是否多选, 默认true
                                        .multiSelect(false)
                                        // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                                        .rememberSelected(false)
                                        // “确定”按钮背景色
                                        .btnBgColor(Color.GRAY)
                                        // “确定”按钮文字颜色
                                        .btnTextColor(Color.BLUE)
                                        // 使用沉浸式状态栏
                                        .statusBarColor(Color.parseColor("#3F51B5"))
                                        // 返回图标ResId
                                        .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material)
                                        // 标题
                                        .title("图片")
                                        // 标题文字颜色
                                        .titleColor(Color.WHITE)
                                        // TitleBar背景色
                                        .titleBgColor(Color.parseColor("#353535"))
                                        // 裁剪大小。needCrop为true的时候配置
                                        .cropSize(1, 1, 200, 200)
                                        .needCrop(true)
                                        // 第一个是否显示相机，默认true
                                        .needCamera(true)
                                        // 最大选择图片数量，默认9
                                        .maxNum(1)
                                        .build();

                                // 跳转到图片选择器
                                ISNav.getInstance().toListActivity(UserInfoActivity
                                        .this, config, REQUEST_LIST_CODE);
                                bottomDialog.dismiss();

                            }
                        });

                    }
                })
                .setLayoutRes(R.layout.bottom_layout)
                .setDimAmount(0.5f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();

    }

    /**
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data != null) {
            //拍照的回调
            String path = data.getStringExtra("result"); // 图片地址
            Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
            Tiny.getInstance().source(path).asFile().withOptions(options).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, String outfile, Throwable t) {
                    if (isSuccess) {
                        userIcon = new File(outfile);
                        Glide.with(UserInfoActivity.this).load(userIcon).into(ivUserInfoAvatar);
                    }
                }

            });


        } else if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");
            String mGalleryPath = pathList.get(0);
            Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
            Tiny.getInstance().source(mGalleryPath).asFile().withOptions(options).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, String outfile, Throwable t) {
                    if (isSuccess) {
                         userIcon = new File(outfile);
                        Glide.with(UserInfoActivity.this).load(userIcon).into(ivUserInfoAvatar);
                    }
                }

            });

        }
    }
    /**
     * 隐藏软键盘(可用于Activity，Fragment)
     */
    public void hideSoftKeyboard( List<View> viewList) {
        if (viewList == null) return;
        for (View v : viewList) {
            if (((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)) != null) {
                ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(v.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 后退
     */
    @OnClick(R.id.iv_activity_user_info_back)
    public void onIvActivityUserInfoBackClicked() {
        checkContent();


    }

    /**
     * 检测内容是否有变化
     */
    private void checkContent() {
        if (!edtActivityUserInfoSummary.getText().toString().trim().equals(getUserInfoBean.getData().getSelf_intro()) || !tvActivityUserInfoName.getText().toString().trim().equals(getUserInfoBean.getData().getName())){
            popDialog();
        }else if (!gender.equals(getUserInfoBean.getData().getGender())){
            popDialog();
        }else {
            //隐藏软键盘
            mViews.add(tvActivityUserInfoName);
            mViews.add(edtActivityUserInfoSummary);
            hideSoftKeyboard(mViews);
            finish();
        }
    }

    private void popDialog() {
        new AlertDialog.Builder(UserInfoActivity.this).setMessage("检测到内容有变化，是都保存修改的内容").setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                saveInfo();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //隐藏软键盘
                mViews.add(tvActivityUserInfoName);
                mViews.add(edtActivityUserInfoSummary);
                hideSoftKeyboard(mViews);
                finish();
            }
        }).show();
    }

    /**
     * 保存
     */
    @OnClick(R.id.tv_activity_user_info_save)
    public void onTvActivityUserInfoSaveClicked() {
        saveInfo();

    }

    private void saveInfo() {
        Log.e("lixiaofei", "saveInfo: "+ gender);
        PutRequest request =  OkGo.<String>put(MyConstant.MODIFY_USER_INFO).params("token",SPUtils.getString(UserInfoActivity.this,"token",""))
                .params("gender",gender).params("name",tvActivityUserInfoName.getText().toString().trim())
                .params("self_intro",edtActivityUserInfoSummary.getText().toString().trim());
        if (userIcon != null){
            request.params("icon",userIcon);
        }
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Gson gson = new Gson();
                GetUserInfoBean userInfoBean = gson.fromJson(s, GetUserInfoBean.class);
                switch (userInfoBean.getCode()){
                    case 1:
                        //成功
                        Intent intent =  new Intent();
                        intent.putExtra("name",userInfoBean.getData().getName());
                        intent.putExtra("intro",userInfoBean.getData().getSelf_intro());
                        intent.putExtra("iconUrl",userInfoBean.getData().getIcon_file());
                        setResult(RESULT_OK,intent);
                        showToastLong("保存成功");
                        //隐藏软键盘
                        mViews.add(tvActivityUserInfoName);
                        mViews.add(edtActivityUserInfoSummary);
                        hideSoftKeyboard(mViews);
                        finish();
                        break;
                    case -1004:
                    case -1002:
                    case -1003:
                    case -152:
                    case -153:
                        showToastLong("保存失败");
                        break;

                }
            }
        });
    }

    /**
     * 点击男
     */
    @OnClick(R.id.ll_activity_user_info_male)
    public void onLlActivityUserInfoMaleClicked() {
        ivActivityUserInfoMale.setImageResource(R.mipmap.resume_choose);
        ivActivityUserInfoFemale.setImageResource(R.mipmap.resume_unchoose);
        gender = "男";
    }

    /**
     * 点击女
     */
    @OnClick(R.id.ll_activity_user_info_female)
    public void onLlActivityUserInfoFemaleClicked() {
        ivActivityUserInfoFemale.setImageResource(R.mipmap.resume_choose);
        ivActivityUserInfoMale.setImageResource(R.mipmap.resume_unchoose);
        gender = "女";
    }


    /**
     * 点击头像
     */
    @OnClick(R.id.iv_user_info_avatar)
    public void onViewClicked() {
        openGarllary();
    }
}
